package com.whut.www.dialogmenupopwindow;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private PopupWindow mPopupWindow;
    private View mView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mView = LayoutInflater.from(this).inflate(R.layout.popwindow, null);
        mPopupWindow = new PopupWindow(mView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT);
        //设置点击其它区域,PopupWindow不消失
        mPopupWindow.setOutsideTouchable(false);
        ImageView imageView_collection = (ImageView) mView.findViewById(R.id.iv_collection);
        ImageView imageView_back = (ImageView) mView.findViewById(R.id.iv_back);
        ImageView imageView_share = (ImageView) mView.findViewById(R.id.iv_share);
        //imageView_back.setOnClickListener();
        //imageView_collection.setOnClickListener();
        //imageView_share.setOnClickListener();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_AlertDialog:
                //警示对话框
                alertDialog();
                break;
            case R.id.btn_NormalListDialog:
                //列表对话框
                listDialog();
                break;
            case R.id.btn_SingleChoiceItems:
                //单选列表对话框
                singleChoiceItemsDialog();
                break;
            case R.id.btn_MultiChoiceItemsDialog:
                //多选列表对话框
                multiChoiceItemsDialog();
                break;
            case R.id.btn_AdapterDialog:
                //适配器列表对话框
                adapterDialog();
                break;

            case R.id.btn_CustomDialog:
                //自定义对话框
                customDialog();
                break;
            case R.id.btn_ProgressDialog:
                //进度对话框
                progressDialog();
                break;
            case R.id.btn_PopupMenu:
                popupMenu(view);
                break;
            case R.id.btn_PopupWindow:
                popupWindow();
                break;
            case R.id.btn_ContextMenu:
                Intent intent = new Intent(this, ContextMenuActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 对话框的操作步骤：
     * step1：创建Builder构建器
     * step2：通过builder对象，设置各种信息：比如title，icon。。。各种按钮
     * step3：创建对话框对象：builder.create()-->dialog
     * step4：显示dialog.show()
     */
    private void alertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //添加View,展示在icon和title下面
        //builder.setView(R.layout.item_dialog);
        builder.setTitle("确认对话框").setIcon(R.mipmap.ic_launcher_round).setMessage("Are you lucky?");
        //添加确认按钮
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "you are lucky!", Toast.LENGTH_SHORT).show();
            }
        });
        //添加否认按钮
        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "I am sorry!", Toast.LENGTH_SHORT).show();
            }
        });
        //添加中立按钮
        builder.setNeutralButton("Neutral", null);
        //用于点击其他的地方，对话框不消失。
        builder.setCancelable(false);
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        //消失
        //alertDialog.dismiss();
    }

    private void listDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置title的颜色").setIcon(android.R.drawable.btn_star);
        final String[] colors = getResources().getStringArray(R.array.colors);
        /**
         * 设置对话框要展示的列表内容
         * 第一个参数：CharSequence[] items,列表上所展示的文字内容
         * 第二个参数：OnClickListener listener，监听器
         */
        builder.setItems(R.array.colors, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setTitle(colors[which]);
                switch (which) {
                    case 0:
                        Toast.makeText(MainActivity.this, "RED", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this, "GREEN", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(MainActivity.this, "BLUE", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }


    /**
     * @param menu   要显示icon的菜单
     * @param showed 是否展示
     */
    private void showMenuIcon(Menu menu, boolean showed) {
        Class<? extends Menu> aClass = menu.getClass();
        try {
            Method method = aClass.getDeclaredMethod("setOptionalIconsVisible", boolean.class);
            method.setAccessible(true);
            method.invoke(menu, true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private void singleChoiceItemsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置字体大小").setIcon(android.R.drawable.btn_radio);
        final String[] fontSizeNames = getResources().getStringArray(R.array.font_size_name);
        /**
         * setSingleChoiceItems:用于设置显示单选的列表框
         * 第一个参数：CharSequence[] items,列表上要展示的文字内容
         * 第二个参数：int checkedItem, 默认被选中的item的下标，如果没有设置些-1.
         * 第三个参数：OnClickListener listener，
         */
        builder.setSingleChoiceItems(fontSizeNames, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setTitle(fontSizeNames[which]);
                //dialog消失
                //dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }

    private void multiChoiceItemsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择您的爱好").setIcon(android.R.drawable.btn_minus);
        final String[] hobbys = getResources().getStringArray(R.array.hobbys);
        //记录item的选中状态
        final boolean[] checkedItems = new boolean[hobbys.length];
        /**
         * setMultiChoiceItems：设置多选列表
         * 第一个参数：CharSequence[] items, 要展示的列表的信息
         * 第二个参数：boolean[] checkedItems, 每一个item是否被选中的数组。
         * 第三个参数：OnMultiChoiceClickListener listener
         */
        builder.setMultiChoiceItems(hobbys, checkedItems, new DialogInterface
                .OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                //记录点击后item的状态
                checkedItems[which] = isChecked;
            }
        });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < checkedItems.length; i++) {
                    sb.append(checkedItems[i] ? (hobbys[i] + "\t") : "");
                }
                Toast.makeText(MainActivity.this, sb, Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();

    }

    private void adapterDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("设置").setIcon(android.R.drawable.btn_dialog);
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        String[] names = getResources().getStringArray(R.array.names);
        final String[] icons = getResources().getStringArray(R.array.icons);
        for (int i = 0; i < names.length; i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", names[i]);
            int iconId = getResources().getIdentifier(icons[i], "drawable", getPackageName());
            map.put("iconId", iconId);
            list.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.item_dialog, new
                String[]{"name", "iconId"}, new int[]{R.id.textView, R.id.imageView});
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                switch (which) {
                    case 0:
                        //打开wifi
                        intent.setAction(Settings.ACTION_WIFI_SETTINGS);
                        break;

                    case 1:
                        //打开蓝牙
                        intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
                        break;
                    case 2:
                        //声音
                        intent.setAction(Settings.ACTION_SOUND_SETTINGS);
                        break;
                    case 3:
                        //日期
                        intent.setAction(Settings.ACTION_DATE_SETTINGS);
                        break;
                }
                startActivity(intent);
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();

    }

    private void customDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View titleView = layoutInflater.inflate(R.layout.custom_titleview, null);
        ImageView imageView = (ImageView) titleView.findViewById(R.id.iv_customTitle);
        TextView textView = (TextView) titleView.findViewById(R.id.tv_customTitle);
        textView.setText("来自地狱亡灵之手");
        imageView.setImageResource(R.mipmap.ic_launcher);
        //设置自定义title
        builder.setCustomTitle(titleView);
        View customView = layoutInflater.inflate(R.layout.customdialog, null);
        final EditText editText_name = (EditText) customView.findViewById(R.id.et_name);
        final EditText editText_password = (EditText) customView.findViewById(R.id.et_password);
        //设置自定义的view
        builder.setView(customView);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String name = editText_name.getText().toString();
                String password = editText_password.getText().toString();
                Toast.makeText(MainActivity.this, name + "      " + password, Toast.LENGTH_SHORT)
                        .show();
            }
        });
        builder.create().show();
    }

    private void progressDialog() {
        //progressdialog：是一个唯一可以在子线程中操作的控件
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("下载进度");
        progressDialog.setIcon(R.mipmap.ic_launcher);
        progressDialog.setMessage("急速加载中");
        progressDialog.setMax(100);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "确定", new DialogInterface
                .OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "取消", new DialogInterface
                .OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        progressDialog.setButton(ProgressDialog.BUTTON_NEUTRAL, "中立", new DialogInterface
                .OnClickListener() {


            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        progressDialog.show();
        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    progressDialog.setProgress(i);
                    SystemClock.sleep(100);
                }
                progressDialog.setProgress(100);
                progressDialog.dismiss();
                // progressDialog是否展示
                progressDialog.isShowing();
            }
        }.start();
    }

    private void popupWindow() {
        // 默认不可取消
        //popupWindow.showAsDropDown(view, 0, 0);
        Drawable drawable = getResources().getDrawable(R.drawable.contentback);
        // 设置可取消
        //mPopupWindow.setOutsideTouchable(true);
        //mPopupWindow.setBackgroundDrawable(drawable);
        // 设置可以取消
        //mPopupWindow.setFocusable(true);
        mPopupWindow.showAtLocation(mView, Gravity.CENTER, 0, 0);
    }

    private void popupMenu(View view) {
        /**
         * 创建popupMenu对象：
         * 第一个参数：context：上下文
         * 第二个参数：View anchor:词意：锚点.操作谁,为谁创建菜单。此处是button。
         */
        PopupMenu popupMenu = new PopupMenu(this, view);
        Menu menu = popupMenu.getMenu();
        //显示菜单的icon
        showMenuIcon(menu, true);
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popup, menu);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.add:
                        Toast.makeText(MainActivity.this, "add", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.sub:
                        Toast.makeText(MainActivity.this, "sub", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.color:
                        Toast.makeText(MainActivity.this, "color", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.call:
                        Toast.makeText(MainActivity.this, "call", Toast.LENGTH_SHORT).show();
                        break;
                }
                return false;
            }
        });
        popupMenu.setGravity(Gravity.CENTER_VERTICAL);
        popupMenu.show();
        //popupMenu.dismiss();
    }

    public void popUpOverflow() {
        /**
         * 定位PopupWindow，让它恰好显示在Action Bar的下方。 通过设置Gravity，确定PopupWindow的大致位置。
         * 首先获得状态栏的高度，再获取Action bar的高度，这两者相加设置y方向的offset样PopupWindow就显示在action
         * bar的下方了。 通过dp计算出px，就可以在不同密度屏幕统一X方向的offset.但是要注意不要让背景阴影大于所设置的offset，
         * 否则阴影的宽度为offset.
         */
        // 获取状态栏高度
        Rect frame = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        // 状态栏高度：frame.top
        int xOffset = frame.top + getSupportActionBar().getHeight() - 0;//减去阴影宽度，适配UI.
        int yOffset = Dp2Px(this, 5f); //设置x方向offset为5dp
        View parentView = getLayoutInflater().inflate(R.layout.activity_main, null);
        View popView = getLayoutInflater().inflate(R.layout.popupwindow_imp_overflow, null);
        PopupWindow popWind = new PopupWindow(popView, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);
        //popView即popupWindow的布局，ture设置focusAble.

        //必须设置BackgroundDrawable后setOutsideTouchable(true)才会有效。这里在XML中定义背景，所以这里设置为null;
        popWind.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        popWind.setOutsideTouchable(true); //点击外部关闭。
        //设置一个动画。
        popWind.setAnimationStyle(android.R.style.Animation_Dialog);
        //设置Gravity，让它显示在右上角。
        popWind.showAtLocation(parentView, Gravity.RIGHT | Gravity.TOP, yOffset, xOffset);
    }

    public int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }


    //Activity加载即执行onCreateOptionsMenu(只执行一次)、onPrepareOptionsMenu(每次点击更多菜单项都执行)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, 666, 6, "popImpOverFlow").setIcon(android.R.drawable.ic_menu_gallery);
        Log.i("MainActivity", "---onCreateOptionsMenu()--->" + "创建OptionsMenu");
        //显示菜单的icon
        showMenuIcon(menu, true);
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.options, menu);
        //第一个参数groupId、第二个参数itemId、第三个参数order、第四个参数title
        MenuItem menuItem = menu.add(Menu.NONE, 6, 8, "code");
        // 设置icon
        menuItem.setIcon(R.mipmap.ic_launcher);
        // 设置是否显示在actionBar上
        menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        //添加子菜单
        menu.addSubMenu(Menu.NONE, 7, 8, "subCode");
        return super.onCreateOptionsMenu(menu);
    }

    //每次点击optionsMenu的更多菜单选项的三个点,都会执行,故可动态更改menu的item
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        Log.i("MainActivity", "---onPrepareOptionsMenu()--->" + "准备optionsMenu");
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                Toast.makeText(this, "add", Toast.LENGTH_SHORT).show();
                break;
            case R.id.action_sub:
                Toast.makeText(this, "sub", Toast.LENGTH_SHORT).show();
                break;
            case R.id.action_random:
                Random random = new Random();
                int nextInt = random.nextInt(255);
                Toast.makeText(this, String.valueOf(nextInt), Toast.LENGTH_SHORT).show();
                break;
            case 6:
                Toast.makeText(this, "code", Toast.LENGTH_SHORT).show();
                break;
            case 666:
                // 展示popupWindow
                popUpOverflow();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

}
